<?php

namespace App\Services\Echarts;
use WechatUserService;
use TestingDetailService;
use UserRecordService;
use TestingConfig;
use App\Helper\Tool;
use TestingVisitService;
use Cache;
class DecreaseEchartHelper{
    protected $tag = 'DW.echart';


    /**获取所有数据
     * @param $tid
     * @return mixed
     */
    public function getData($tid,$start_time,$end_time){
        $cacheKey = getCacheKey('testing.cache_key.DWechart.data');
        $cacheKey = $cacheKey .date('Y-m-d',strtotime($start_time))."-".date('Y-m-d',strtotime($end_time))."_".$tid;
        $datas = Cache::tags($this->tag)->remember($cacheKey, 10,function () use ($tid,$start_time,$end_time) {
            $data=[];
            $res = $this -> formate($tid,$start_time,$end_time);
            $fat = $this->Fat($res);
            $baseObesityIndex = $this->baseObesityIndex($res);
            $data['visit']=$this->visit($tid);
            $data['sleep']=$this->sleep($res);
            $data['physical']=$this->physical($res);
            $data['sex']=$this->sex($fat);
            $data['status']=$this->status($res);
            $data['fatScale'] = $this->fatScale($fat);
            $data['obesityIndex']=$this->obesityIndex($baseObesityIndex);
            $data['obesityStatus']=$this->obesityStatus($baseObesityIndex);
            $data['intestineHealth']=$this->intestineHealth($baseObesityIndex);
            $data['obesityDiet']=$this->obesityDiet($baseObesityIndex);
            $data['resistance']=$this->resistance($baseObesityIndex);
            $data['province']=$this->province();
            $data['provinceData'] = $this->provinceData($res);
            return $data;
        });
        return $datas;
    }

    /**男女肥胖比例
     * @param $tid
     * @param $sex
     * @return mixe
     */
    protected function fatScale($res){
            $fat =TestingConfig::getValue('DW.fat.overweight.obesity.bmi');
            $over =TestingConfig::getValue('DW.fat.overweight.over.bmi');
            $normal=TestingConfig::getValue('DW.fat.overweight.normal.bmi');
            $weight=[];
            foreach($res as $k => $v){
                if($v['bmi'] >= $fat){
                    $weight[$k]=0;//肥胖
                }elseif($v['bmi'] >= $over  && $v['bmi'] < $fat){
                    $weight[$k]=1;//超重
                }elseif($v['bmi'] >= $normal  && $v['bmi'] < $over){
                    $weight[$k]=2;//正常
                }else{
                    $weight[$k]=3;//体重过低
                }
            }
            $totle = count($weight);
            $num = array_count_values($weight);
            $data['first']=isset($num['0']) ? $num['0'] : 0;
            $data['second']=isset($num['1']) ? $num['1'] : 0;
            $data['three']=isset($num['2']) ? $num['2'] : 0;
            $data['four']=isset($num['3']) ? $num['3'] : 0;
            return $data;
    }


    /**肥胖基础
     * @param $tid
     * @return mixed
     */
    protected function Fat($res){
        $data = [];
        foreach($res as $k => $v){
            foreach($v['answer'] as $key => $value){
                if($value['index'] == 3 && $value['weight'] == 1 ){
                    $data[$k]['sex']=1;
                }elseif($value['index'] == 3 && $value['weight'] == 0 ){
                    $data[$k]['sex']=0;
                }
                if($value['index'] == 21){
                    $data[$k]['bmi']=$value['weight'];
                }
            }
        }
        return $data;
    }

    /**睡眠时间
     * @param $tid
     * @return array
     */
    protected function sleep($res){
            $sleep=[];
            $data=[];
            foreach($res as $k => $v) {
                foreach ($v['answer'] as $key => $value) {
                    if ($value['index'] == 13) {
                        $sleep[$k] = $value['weight'];
                    }
                }
            }
            $num = array_count_values($sleep);
            $num['1'] = isset($num['1']) ? $num['1']:0;
            $num['-1'] = isset($num['-1']) ? $num['-1']:0;
            $data['over'] = 0;
            if(!empty($num['-1']+$num['1'])){
                $data['over'] =round(100*$num['-1']/($num['-1']+$num['1']));
            }
            $data['normal'] =100-$data['over'];
            return $data;
    }

    /**身材状态
     * @param $tid
     * @return mixed
     */
    protected function physical($res){
            $status=[];
            foreach($res as $k => $v) {
                foreach ($v['answer'] as $key => $value) {
                    if ($value['index'] == 5) {
                        $status[$k] = $value['weight'];
                    }
                }
            }
            $totle = count($status);
            $num = array_count_values($status);
            $data['first']=isset($num['1']) ? round(100*$num['1']/$totle) : 0;
            $data['second']=isset($num['2']) ? round(100*$num['2']/$totle) : 0;
            $data['three']=isset($num['3']) ? round(100*$num['3']/$totle) : 0;
            $data['four']=isset($num['4']) ? round(100*$num['4']/$totle) : 0;
            $data['five']=100-$data['first']-$data['second']-$data['three']-$data['four'];
            return $data;
    }

    /*健康状态
     * @param $tid
     * @return mixed
     */
    protected function status($res){
            $status=[];
            foreach($res as $k => $v) {
                foreach ($v['answer'] as $key => $value) {
                    if ($value['index'] == 17) {
                        $status[$k] = $value['answer'];
                    }
                }
            }
            foreach($status as $k => $v){
                if(strpos($v,'|||')){
                    $arr = explode('|||',$v);
                    foreach($arr as $key => $value){
                        array_push($status,$value);
                    }
                    unset($status[$k]);
                }
            }
            $num = array_count_values($status);
            $data['first']=isset($num['糖尿病']) ? $num['糖尿病'] : 0;
            $data['second']=isset($num['高血压']) ? $num['高血压'] : 0;
            $data['three']=isset($num['高血脂']) ? $num['高血脂'] : 0;
            $data['four']=isset($num['心血管疾病']) ? $num['心血管疾病'] : 0;
            $data['five']=isset($num['肝肾疾病']) ? $num['肝肾疾病'] : 0;
            $data['six']=isset($num['多囊卵巢综合征']) ? $num['多囊卵巢综合征'] : 0;
            $data['seven']=isset($num['没有上述疾病']) ? $num['没有上述疾病'] : 0;
            return $data;
    }

    /**省份
     * @return array
     */
    protected function province(){
        $data=['北京','天津','上海','重庆','河北','山西','辽宁','吉林','黑龙江','江苏','浙江','安徽','福建','江西','山东','河南','湖北','湖南','广东','海南','四川','贵州','云南','陕西','甘肃','青海','内蒙古','广西','西藏','宁夏','新疆','香港','澳门','台湾'];
        return $data;
    }

    /**返回省份人数数据
     * @param $tid
     * @return array
     */
    public function provinceData($res){
            $uidarr = [];
            $province=[];
            $data = [];
            foreach($res as $k => $v){
                $uidarr[$k]=$v['uid'];
            }
            $uids = array_unique($uidarr);
            foreach($uids as $k => $v){
                $results = WechatUserService::getByUid($v);
                if($results){
                    $province[$k]=$results['province'];
                }
            }
            $province = array_filter($province);
            $totle = count($province);
            if($totle>0){
                $result = array_count_values($province);
                $data = $this->province();
                foreach($data as $k => $v){
                    foreach($result as $key => $value){
                        if($v == $key){
                            $data[$k]=(int)$value;
                        }
                    }
                }
                foreach($data as $k => $v){
                    if(is_string($v)){
                        $data[$k]=0;
                    }
                    $data[$k]=round(100*$v/$totle);
                }
                $data[0]=100-array_sum($data)+$data[0];
            }

            return $data;
    }

    protected function visit($tid){
            $data['pv']=TestingVisitService::getPv($tid);
            $data['uv']=TestingVisitService::getUv($tid);
            $data['ip']=TestingVisitService::getIp($tid);
            $data['avgtime']=UserRecordService::avgTime($tid);
            return $data;
    }

    /**性别比例
     * @param $tid
     * @return array
     */
    protected function sex($fat){
        $result = [];
        $sex = [];
       if($fat){
           foreach($fat as $k => $v){
               $sex[$k]=$v['sex'];
           }
       }
        $totle = empty(count($sex)) ? 1 : count($sex);
        $result = array_count_values($sex);
        $result[0]=isset($result[0])?$result[0]:0;
        $result[0]=round(100*$result[0]/$totle);
        $result[1]=100-$result[0];
       return $result;
    }

    /**肥胖指数统计
     * @param $tid
     */
    protected function obesityIndex($base){
            $baseData = isset($base['obesity']) ? $base['obesity'] :[];
            $count =  array_count_values($baseData);
            for($i=0;$i<=5;$i++){
                $count[$i] = isset($count[$i]) ? $count[$i] : 0;
            }
            foreach($count as $k => $v){
                if($k<0){
                    $count[0] = $count[0]+$count[$k];
                    unset($count[$k]);
                }
                if($k>5){
                    $count[5] = $count[5]+$count[$k];
                    unset($count[$k]);
                }

            }
            ksort($count);
            $data['describe'] = ['X','☆','☆☆','☆☆☆','☆☆☆☆','☆☆☆☆☆'];
            $data['index']=$count;
            return $data;
    }

    /**肥胖人群饮食习惯
     * @param $tid
     */
    protected function obesityDiet($origin){
            $originData = isset($origin['originData']) ? $origin['originData'] : [];
            $data = [];
            $diet = [];
            foreach($originData as $k => $v){
                foreach($v['answer'] as $key => $value){
                    if($value['index'] == 7){
                        $dietArr = explode('|||',$value['answer']);
                        $dietArr = array_filter($dietArr);
                        foreach($dietArr as $keys => $values){
                            array_push($diet,$values);
                        }
                    }
                }
            }
        $totle = count($diet);
        $num = array_count_values($diet);
        $data['first']=isset($num['经常无法吃早餐']) ? round(100*$num['经常无法吃早餐']/$totle) : 0;
        $data['second']=isset($num['三餐中晚餐最丰富']) ? round(100*$num['三餐中晚餐最丰富']/$totle) : 0;
        $data['three']=isset($num['偏好重口味，比如重油、甜的、辣的或咸的食物']) ? round(100*$num['偏好重口味，比如重油、甜的、辣的或咸的食物']/$totle) : 0;
        $data['four']=isset($num['一周总有3次以上吃到撑']) ? round(100*$num['一周总有3次以上吃到撑']/$totle) : 0;
        $data['five']=isset($num['经常喝甜饮料，一周3次以上']) ? round(100*$num['经常喝甜饮料，一周3次以上']/$totle) : 0;
        $data['six']=isset($num['常备各种包装类零食，如糕点、卤制品等']) ? round(100*$num['常备各种包装类零食，如糕点、卤制品等']/$totle) : 0;
        $data['seven']=isset($num['蔬菜并不是每一顿饭都有']) ? round(100*$num['蔬菜并不是每一顿饭都有']/$totle) : 0;
        $data['eight']=isset($num['总是忍不住吃街边的小吃，一周总会吃3次以上']) ? round(100*$num['总是忍不住吃街边的小吃，一周总会吃3次以上']/$totle) : 0;
        $data['nine']=100-$data['first']-$data['second']-$data['three']-$data['four']-$data['five']-$data['six']-$data['seven']-$data['eight'];
        return $data;
    }

    /**肥胖人群饮食状态
     * @param $tid
     * @return mixed
     */
    protected function obesityStatus($origin){
            $originData = isset($origin['originData']) ? $origin['originData'] : [];
            $status = [];
            foreach($originData as $k => $v){
                foreach($v['answer'] as $key => $value){
                    if($value['index'] == 8){
                        array_push($status,$value['weight']);
                    }
                }
            }
            $totle = count($status);
            $num = array_count_values($status);
            $data['first']=isset($num['1']) ? round(100*$num['1']/$totle) : 0;
            $data['second']=isset($num['-1']) ? round(100*$num['-1']/$totle) : 0;
            $data['three']=isset($num['2']) ? round(100*$num['2']/$totle) : 0;
            $data['four']=100-$data['first']-$data['second']-$data['three'];
            return $data;
    }

    /**肥胖人群肠道健康状况
     * @param $tid
     * @return mixed
     */
    protected function intestineHealth($origin){
        $originData = isset($origin['originData']) ? $origin['originData'] : [];
            $health = [];
            foreach($originData as $k => $v){
                foreach($v['answer'] as $key => $value){
                    if($value['index'] == 10){
                        array_push($health,$value['weight']);
                    }
                }
            }
            $totle = count($health);
            $num = array_count_values($health);
            $data['first']=isset($num['1']) ? round(100*$num['1']/$totle) : 0;
            $data['second']=isset($num['2']) ? round(100*$num['2']/$totle) : 0;
            $data['three']=100-$data['first']-$data['second'];
            return $data;
    }

    /**
     * @param $tid
     */
    protected function resistance($origin){
        $originData = isset($origin['originData']) ? $origin['originData'] : [];
            $resistance = [];
            foreach($originData as $k => $v){
                foreach($v['answer'] as $key => $value){
                    if($value['index'] == 14){
                        array_push($resistance,$value['weight']);
                    }
                }
            }
            $totle = count($resistance);
            $num = array_count_values($resistance);
            $data['first']=isset($num['1']) ? round(100*$num['1']/$totle) : 0;
            $data['second']=isset($num['2']) ? round(100*$num['2']/$totle) : 0;
            $data['three']=isset($num['3']) ? round(100*$num['3']/$totle) : 0;
            $data['four']=isset($num['4']) ? round(100*$num['4']/$totle) : 0;
            $data['five']=isset($num['5']) ? round(100*$num['5']/$totle) : 0;
            $data['six']=isset($num['6']) ? round(100*$num['6']/$totle) : 0;
            $data['seven']=100-$data['first']-$data['second']-$data['three']-$data['four']-$data['five']-$data['six'];
            return $data;
    }

    /**@25肥胖指数
     * @param $tid
     * @return array
     */
    protected function baseObesityIndex($res){
            $data = [];
            foreach($res as $k => $v){
                foreach($v['answer'] as $key => $value) {
                    if($value['index'] == 25){
                        $data['obesity'][$k]=$value['weight'];
                        if($value['weight']>=2){
                            $data['originData'][$k]=$v;
                        }
                    }
                }
            }
            return $data;
    }

    /**格式化结果
     * @param $tid
     * @return mixed
     */
    protected function formate($tid,$start_time,$end_time){
            $res = UserRecordService::getByTidTime($tid,$start_time,$end_time);
            $data = [];
            foreach($res as $k => $v){
                $answerArr =Tool::strToArr($v['final_answers']);
                $data[$k]['answer']=$answerArr;
                $data[$k]['uid']=$v['uid'];
            }
            return $data;
    }



}